package com.ruoyi.premises.utils;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class QiniuKodoFile {
    /**
     * 构造一个带指定 Region 对象的配置类，因为我的是华南机房，所以为Region.region2()
     */
   // Configuration cfg = new Configuration(Region.region2());
    @Value("${qiniu.kodo.accessKey}")
    String accessKey;
    @Value("${qiniu.kodo.secretKey}")
    String secretKey;
    @Value("${qiniu.kodo.bucket}")
    String bucket;
    @Value("${qiniu.kodo.domain}")
    String domain;
    /**
     * 文件名前缀
     */
    String prefix = "";
    /**
     * 每次迭代的长度限制，最大1000，推荐值 1000
     */
    int limit = 1000;
    /**
     * 指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
     */
    String delimiter = "";

    public String uploadFile(MultipartFile file) throws Exception {
        try {
            byte[] fileBytes = file.getBytes();
            //2、创建日期目录分隔
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = dateFormat.format(new Date());
            //3、获取文件名
            String originalFilename = file.getOriginalFilename();
            //   String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //   String filename = datePath+"/"+ UUID.randomUUID().toString().replace("-", "")+ suffix;
            String filename = datePath+"/"+ UUID.randomUUID().toString().replace("-", "")+ originalFilename;
            //4.构造一个带指定 Region 对象的配置类
            //存储的地区(根据自己的对象空间的地址选
            Configuration cfg = new Configuration(Zone.zone1());
            //后来换了稳定的新加坡的空间并且绑定了个人域名没有做https的配置这时候要配置这个选项
            /*
             *域名不支持https访问会报错ssl验证error
             *cfh.useHttpsDomains=false 关闭实列即可 默认是开启的
             */

            UploadManager uploadManager = new UploadManager(cfg);
            //5.获取七牛云提供的 token
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            uploadManager.put(fileBytes, filename, upToken);
            return "http://"+ domain+"/"+filename;
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public String uploadFiles(MultipartFile file) throws Exception {
        try {
            byte[] fileBytes = file.getBytes();
            //2、创建日期目录分隔
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = dateFormat.format(new Date());
            //3、获取文件名
            String originalFilename = file.getOriginalFilename();
         //   String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
         //   String filename = datePath+"/"+ UUID.randomUUID().toString().replace("-", "")+ suffix;
            String filename = datePath+"/"+ UUID.randomUUID().toString().replace("-", "")+ originalFilename;
            //4.构造一个带指定 Region 对象的配置类
            //存储的地区(根据自己的对象空间的地址选
            Configuration cfg = new Configuration(Zone.zone1());
            //后来换了稳定的新加坡的空间并且绑定了个人域名没有做https的配置这时候要配置这个选项
            /*
             *域名不支持https访问会报错ssl验证error
             *cfh.useHttpsDomains=false 关闭实列即可 默认是开启的
             */

            UploadManager uploadManager = new UploadManager(cfg);
            //5.获取七牛云提供的 token
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            uploadManager.put(fileBytes, filename, upToken);
            System.err.println("============="+filename);
            return "http://"+ domain+"/"+filename;
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }
    /**
     * 处理多文件
     * @param multipartFiles
     * @return
     */
    public Map<String, List<String>> uploadImages(MultipartFile[] multipartFiles) throws Exception {
        Map<String, List<String>> map = new HashMap<>();
        List<String> imageUrls = new ArrayList<>();
        for(MultipartFile file : multipartFiles){
            imageUrls.add(uploadFiles(file));
        }
        map.put("imageUrl",imageUrls);
        return map;
    }
    /**
     * 列举空间文件列表
     */
    public void listSpaceFiles() {
        Auth auth = Auth.create(accessKey, secretKey);
        Configuration cfg = new Configuration(Region.region2());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, prefix, limit, delimiter);
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                System.out.println(item.key);
                System.out.println(item.fsize / 1024 + "kb");
                System.out.println(item.mimeType);
            }
        }
    }


    /**
     * 上传本地文件
     */
//    public String upload(String localFilePath) {
//        UploadManager uploadManager = new UploadManager(cfg);
//        /**
//         *  如果是Windows情况下，格式是 D:\\qiniu\\test.png
//         * 以文件最低级目录名作为文件名
//         */
//        String[] strings = localFilePath.split("\\\\");
//        String key = strings[strings.length - 1];
//        Auth auth = Auth.create(accessKey, secretKey);
//        String upToken = auth.uploadToken(bucket);
//        try {
//            Response response = uploadManager.put(localFilePath, key, upToken);
//            //解析上传成功的结果
//            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//            System.err.println(putRet.key);
//            return "http://rtef2r038.hn-bkt.clouddn.com/"+putRet.key;
//        } catch (QiniuException ex) {
//            Response r = ex.response;
//            System.err.println(r.toString());
//            try {
//                System.err.println(r.bodyString());
//            } catch (QiniuException ex2) {
//                //ignore
//            }
//        }
//        return  null;
//    }

    /**
     * 获取下载文件的链接
     *
     * @param fileName 文件名称
     * @return 下载文件的链接
     */
    public String getFileUrl(String fileName) throws UnsupportedEncodingException {
        String encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
        String finalUrl = String.format("%s/%s", "http://" + domain, encodedFileName);
        System.out.println(finalUrl);
        return finalUrl;
    }

    /**
     * 批量删除空间中的文件
     *
     * @param fileList 文件名称列表
     */
    public void deleteFile(String[] fileList) {
        Auth auth = Auth.create(accessKey, secretKey);
        Configuration cfg = new Configuration(Region.region2());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            //单次批量请求的文件数量不得超过1000
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(bucket, fileList);
            Response response = bucketManager.batch(batchOperations);
            BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
            for (int i = 0; i < fileList.length; i++) {
                BatchStatus status = batchStatusList[i];
                String key = fileList[i];
                System.out.print(key + "\t");
                if (status.code == 200) {
                    System.out.println("delete success");
                } else {
                    System.out.println(status.data.error);
                }
            }
        } catch (QiniuException ex) {
            System.err.println(ex.response.toString());
        }
    }


}

